package org.mengyun.tcctransaction.sample.service;

import org.mengyun.tcctransaction.api.TransactionContext;
import org.mengyun.tcctransaction.sample.domain.dto.OrderDto;
import org.mengyun.tcctransaction.sample.domain.dto.TransactionContextDto;
import org.mengyun.tcctransaction.sample.domain.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

/**
 * xuejianxin
 */
@Service("productService")
public class ProductServiceProxy implements IProductService {

	@Autowired
	RestTemplate restTemplate;

	@Override
	// @Compensable(confirmMethod = "reduceStock", cancelMethod =
	// "reduceStock", propagation = Propagation.SUPPORTS)//此注解没有也可
	public String reduceStock(TransactionContext tc /* 此参数会被切面动态注入参数 */, OrderDto od) {
		return callReduceStock(tc, od);
	}

	private String callReduceStock(TransactionContext tc, OrderDto od) {
		TransactionContextDto<OrderDto> tcd = new TransactionContextDto<>(tc, od);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<Object> httpEntity = new HttpEntity<Object>(JSONObject.toJSON(tcd), headers);
		//System.out.println(httpEntity.toString());
		String url = "http://localhost:9002/reduceStock";
		ResponseEntity<String> res = restTemplate.postForEntity(url, httpEntity, String.class);
		//System.out.println(res);
		if (res.getStatusCode().is2xxSuccessful()) {
			return "ok";
		}
		throw new RuntimeException("请求reduceStock 错误");
	}

}
